let errinfo = require('../errinfo.js');
let responseJsonUtils = require('../utils/responseJsonUtils');
let userUtils = require('../utils/userUtils');

let login = module.exports = {};

login.checkInput = function (req, res, next) {
    let body = req.body;
    let cellphone = body.cellphone;
    let password = body.password;

    if (!cellphone) {
        next(responseJsonUtils.json(errinfo.userLoginCellphoneEmpty, 403));
        return;
    }
    if (!password) {
        next(responseJsonUtils.json(errinfo.userLoginPasswordEmpty, 403));
        return;
    }

    next();
};
login.checkUserExist = function (req, res, next) {

    let body = req.body;
    let cellphone = body.cellphone;

    let query = User.findOne({
        cellphone: cellphone,
    });

    query.exec(function (err, user) {
        if (err) {
            next(responseJsonUtils.json(errinfo.mongodb.internalError));
            return;
        }
        if (user) {
            req.user = user;
            next();
        } else {
            // no login
            next(responseJsonUtils.json(errinfo.userNotExist, 401));
        }
    });
};
login.comparePassword = function (req, res, next) {

    let user = req.user;
    let password = req.body.password;


    user.comparePassword(password, function (err, isMatch) {
        if (err) {
            next(responseJsonUtils.json(errinfo.mongodb.internalError));
            return;
        }
        if (isMatch) {
            next();

        } else {
            // password error
            // res.status(401).json();
            next(responseJsonUtils.json(errinfo.userPasswordError, 401));
        }
    });
};
// login
login.suc = function (req, res, next) {

    res.set('book-session-id', req.session.id);
    let result = Object.assign({}, req.session.user, {
        token: req.session.id
    });
    // res.cookie('connect.id', req.session.id);
    res.status(200).json(result);
};